﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Data.SqlClient;
using System.Net.NetworkInformation;
using System.Timers;
using System.Windows.Threading;
using DocumentFormat.OpenXml.Drawing;
using System.Net.Sockets;
using System.Threading.Tasks;


namespace black_screen_mode_server
{
    /// <summary>
    /// DatabasePage.xaml 的交互逻辑
    /// </summary>
    public partial class DatabasePage : Page
    {

        private string connectionString = ProjectTools.configDbConnString;
        private DispatcherTimer timer;
        public DatabasePage()
        {
            InitializeComponent();
            LoadInitialDataFromDatabase();

            Double frequency = Double.Parse(txtFrequency.Text);
            timer = new DispatcherTimer();

            timer.Interval = TimeSpan.FromSeconds(frequency);
            timer.Start();
            LoadComboBox();
        }



        public static class ServerName
        {
            public static string? serverName { get; set; }
        }

        public void Stop()
        {
            this.timer.Stop();
        }
        //连接断开报警sh
        private void CheckConnection(object sender, EventArgs e)
        {
            try
            {
                using SqlConnection connection = new SqlConnection(connectionString);
                connection.Open();
            }
            catch (SqlException)
            {
                timer.Stop();
                MessageBox.Show(("服务器连接已断开！"), "连接提示", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void LoadInitialDataFromDatabase()
        {
            txtFrequency.Text = ProjectTools.ReadConfig("parametersInfo", "frequency");

            //txtFrequency.Text = ConfigurationTools.configuration.GetSection("parametersInfo")["frequency"];
        }


        //确认修改
        private void btnDatabaseConfirm_Click(object sender, RoutedEventArgs e)
        {
            if (txtFrequency.Text.Trim() == "")
            {
                MessageBox.Show("数据库轮询频率不能为空！");
                return;
            }
            if (!double.TryParse(txtFrequency.Text, out double frequency))
            {
                MessageBox.Show("数据库轮询频率必须为数字！");
                return;
            }

            //服务器主机信息验证
            if (txtHostName.Text.Trim() == "")
            {
                MessageBox.Show("服务器主机名不能为空！");
                return;
            }
            try
            {

                ProjectTools.WriteConfig("parametersInfo", "frequency", frequency.ToString());

                MessageBox.Show("更新成功！", "提示");
            }
            catch (Exception)
            {
                MessageBox.Show("更新失败！", "错误");
            }

        }


        //连接测试
        private async void btnServerTest_Click(object sender, RoutedEventArgs e)
        {
            string host = txtHostName.Text;
            int port1 = int.Parse(ProjectTools.ReadConfig("eventDbConnection", "port1"));
            int port2 = int.Parse(ProjectTools.ReadConfig("eventDbConnection", "port2"));

            bool isServerReachable1 = await IsServerReachableAsync(host, port1, 2500);
            bool isServerReachable2 = await IsServerReachableAsync(host, port2, 2500);
            if (isServerReachable1 || isServerReachable2)
            {
                MessageBox.Show("连接测试成功！", "提示");
            }
            else
            {
                MessageBox.Show("连接测试失败！", "提示");
            }
        }

        private async Task<bool> IsServerReachableAsync(string host, int port, int timeout)
        {
            try
            {
                using (var client = new TcpClient())
                {
                    var connectTask = client.ConnectAsync(host, port);
                    var timeoutTask = Task.Delay(timeout);

                    var completedTask = await Task.WhenAny(connectTask, timeoutTask);

                    if (completedTask == timeoutTask)
                    {
                        return false;
                    }
                    await connectTask;
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        private void btnAddServer_Click(object sender, RoutedEventArgs e)
        {

            string newName = Microsoft.VisualBasic.Interaction.InputBox("请输入新的服务器名称：", "命名");

            if (!string.IsNullOrWhiteSpace(newName))
            {
                ComboBoxItem newItem = new ComboBoxItem();
                newItem.Content = newName;
                cmbxSelectServer.Items.Add(newItem);

                using SqlConnection connection = new SqlConnection(connectionString);
                connection.Open();
                string query = "INSERT INTO server_info (server_name) VALUES (@NewName) ";
                SqlCommand command = new SqlCommand(query, connection);
                command.Parameters.AddWithValue("@NewName", newName);
                command.ExecuteNonQuery();
            }

        }

        //选择服务器
        private void LoadComboBox()
        {

            cmbxSelectServer.Items.Clear();
            cmbxSelectServer.Items.Add(ProjectTools.PKSServerName1);
            cmbxSelectServer.Items.Add(ProjectTools.PKSServerName2);
            cmbxSelectServer.SelectedIndex = 0;

            //using (SqlConnection connection = new SqlConnection(connectionString))
            //{
            //    connection.Open();
            //    string query = "SELECT server_name FROM server_info";
            //    SqlCommand command = new SqlCommand(query, connection);
            //    SqlDataReader reader = command.ExecuteReader();

            //    while (reader.Read())
            //    {
            //        cmbxSelectServer.Items.Add(reader["server_name"].ToString());
            //    }
            //    if (cmbxSelectServer.Items.Count > 0)
            //    {
            //        cmbxSelectServer.SelectedIndex = 0;
            //    }

            //    reader.Close();
            //}
        }

        //跟随服务器切换Textbox显示内容
        private void cmbxSelectServer_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if(cmbxSelectServer.SelectedIndex == 0)
            {
               this.txtHostName.Text = ProjectTools.eventDbConnectionModel.Host1;
            }
            else if(cmbxSelectServer.SelectedIndex == 1)
            {
                this.txtHostName.Text = ProjectTools.eventDbConnectionModel.Host2;
            }
        }

        //查询服务器ip及port
        private void LoadServerData(string serverName)
        {
            using SqlConnection connection = new SqlConnection(connectionString);
            string query = "SELECT hostname FROM server_info WHERE server_name = @ServerName";
            SqlCommand command = new SqlCommand(query, connection);
            command.Parameters.AddWithValue("@ServerName", serverName);
            connection.Open();

            SqlDataReader reader = command.ExecuteReader();
            if (reader.Read())
            {
                txtHostName.Text = reader["hostname"].ToString();

            }
        }
    }
}





